<?php
namespace Home\Controller;

class MedicineController extends CommonController{
    
    public function index(){
        if($pid = I('request.pid')){
            $this->uid = I('request.pid');
        }else{
            $pid = '';
        }
        $this->assign('pid',$pid);
        
        $p = I('request.p') ? I('request.p') : 1;
        $list = M('Medicine')->where(array('uid'=>$this->uid))->order('id desc')->page($p.',10')->select();
        if($p == 1){
            $this->assign('list',$list);
            $this->display();
        }else{
            if(empty($list)){
                echo json_encode('err');die;
            }else{
                echo json_encode($list);die;
            }
        }
    }
    
    //记录用药
    public function edit(){
        $Medicine = D('Medicine');
        $create_date = date('Y-m-d');
        if(IS_POST){
            if(I('post.id')){
                $res = $Medicine->save(array(
                    'id'=>I('post.id'),'uid'=>$this->uid,'name'=>I('post.name'),'vol'=>I('post.vol'),
                    'use_time'=>I('post.use_time'),'des'=>I('post.des')
                ));
            }else{
                 $res = $Medicine->add(array(
                    'uid'=>$this->uid,'name'=>I('post.name'),'vol'=>I('post.vol'),
                    'use_time'=>I('post.use_time'),'des'=>I('post.des')
                ));
            }
            
            D('Score')->addMedicine($this->uid);//积分-增加
            
            $res ? die('suc') : die('err');
        }else{
            $Resource = D('Resource');
            $this->assign('medArr',$Resource->where(array('type'=>'medicine'))->select());//药品名
            
            if(I('get.id')){
                $vo = $Medicine->find(intval(I('get.id')));
                $this->assign('vo',$vo);
                $this->assign('useTimeArr',explode(',',$vo['use_time']));//用药时间
                //药物剂量
                $this->assign('medRow',$Resource->where(array('name'=>$vo['name']))->find());
            }
            $this->display();
        }
    }
    
    public function getVol(){
        $list = array();
        if(I('post.pid')){
            $list = D('Resource')->getResByType('medicine',I('post.pid'));
        }
        if(!$list) $list = 'err';
        echo json_encode($list);die;
    }
    
    //改变药品使用状态
    public function changeUse(){
        $res = M('Medicine')->save(array('id'=>I('post.id'),'is_use'=>I('post.is_use')));
        $res ? die('suc') : die('err');
    }
    
    public function del(){
        $Medicine = M('Medicine');
        $id = I('post.id');
        $row = $Medicine->find($id);
        if($row['uid'] == $this->uid){
            $res = $Medicine->delete($id);
            $res ? die('suc') : die('err');
        }else{
            die('err');
        }
    }
    
}